package com.zcw.rabbitmq.chatroom;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DeliverCallback;
import com.zcw.rabbitmq.util.RabbitConnectionUtil;

import java.io.IOException;

/**
 * 发布订阅中的消费者类
 */
public class ChatRoomSubscriber {

    public static final String CONSUMER_TAG = "chat_consumer";


    public static Thread createConsumer(String queueName1){
        if (queueName1 == null || "".equals(queueName1)) return null;
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                 try {
                    final String queueName = queueName1;
                    Connection connection = RabbitConnectionUtil.getSingleRabbitConnection();
                    Channel channel = connection.createChannel();
                    channel.queueDeclare(queueName, true,false, false, null);
                    channel.queueBind(queueName,ChatRoomPublisher.EXCHANGE_NAME,"");
                    DeliverCallback deliverCallback = (consumerTag, delivery)->{
                        String message = new String(delivery.getBody(), "UTF-8");
                        System.out.println("Member [" + Thread.currentThread().getName() + "] received: " + message);
                    };

                    channel.basicConsume(queueName, true, CONSUMER_TAG, deliverCallback, consumerTag -> {});
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        return new Thread(runnable);
    }

}
